package zero.tech.wsnet.net.websocket;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import zero.tech.core.ZeroContext;
import zero.tech.core.event.service.api.EventService;
import zero.tech.wsnet.data.NetEventType;
import zero.tech.wsnet.net.CacheClient;
import zero.tech.wsnet.net.WebClient;

//ws:${ip}:${port}/gate/engine/${uid}
@ServerEndpoint("/engine/{userId}")
public class WebSocketServer {
	@OnOpen
	public void onOpen(Session session,@PathParam("userId") String userId){
		WebClient webClient = CacheClient.getWebClient(session);
		if(webClient!=null){
			webClient.activeClose();
		}
		session.setMaxIdleTimeout(3600000);
		webClient = new WebClient(session,userId);
		webClient.open();
	}
	@OnClose
	public void onClose(Session session){
		System.out.println("open:"+session.isOpen());
		WebClient webClient = CacheClient.getWebClient(session);
		webClient.close();
		EventService netEventService = ZeroContext.getInstance(EventService.class);
		netEventService.engineNotify(NetEventType.ENGINE_WEBSOCKET_CLOSE, webClient);
	}
	@OnMessage
	public void onMessage(Session session,String message){
		WebClient webClient = CacheClient.getWebClient(session);
		webClient.receive(message);
	}
	@OnError
	public void onError(Session session, Throwable cause){
		if (cause != null && cause.getMessage() != null) {
			if (cause.getMessage().startsWith("远程主机强迫关闭了一个现有的连接")
					|| cause.getMessage().startsWith("您的主机中的软件中止了一个已建立的连接")) {
				try {
					session.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}